<?php
/**
 * CheckIn.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-04-09 11:48:04
 * @modified    2023-04-09 11:48:04
 *
 */

namespace App\Models;

use App\Services\AttendanceService;
use App\Services\ImageService;
use Carbon\Carbon;

class CheckIn extends BaseModel
{
    protected $table = 'checkin';
    protected $primaryKey = 'id';
    public const CREATED_AT = 'create_time';
    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'checkin_address',
        'checkout_address',
        'checkin_img',
        'checkout_img',
        'check_status',
        'checkin_time',
        'checkout_time',
        'rel_checkout_time',
        'checkout_delay_desc',
        'user_id',
        'user_name'
    ];

    protected $appends = [
        'check_status_text',
        'checkin_img_url',
        'checkout_img_url',
        'work_time'
    ];

    public function getCheckStatusTextAttribute()
    {
        $checkStatus = $this->check_status;
        if ($checkStatus == AttendanceService::CHECK_STATUS_IN) {
            return '签到';
        }
        if ($checkStatus == AttendanceService::CHECK_STATUS_OUT) {
            return '签退';
        }
        return '';
    }

    public function getCheckinImgUrlAttribute()
    {
        return (new ImageService($this->checkin_img))->getUrl();
    }

    public function getCheckoutImgUrlAttribute()
    {
        return (new ImageService($this->checkout_img))->getUrl();
    }

    /**
     * 签退时间 - 签到时间, 单位: 分钟
     * 签退时间: 真实签退时间 -> 签退时间
     */
    public function getWorkTimeAttribute()
    {
        $last = $this->rel_checkout_time;
        if (!$last) {
            $last = $this->checkout_time;
        }
        $first = $this->checkin_time;
        try {
            return Carbon::parse($last)->diffInMinutes($first, true);
        } catch (\Exception $e) {
            return 0;
        }
    }

    public function work_orders()
    {
        return $this->hasMany(\App\Models\CheckIn\WorkOrder::class, 'checkin_id');
    }
}